package com.i2works.smartluolong.api.controller.company;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.i2works.smartluolong.api.controller.common.CommonItemController;
import com.i2works.smartluolong.utils.base.CompanyMemberIdentityEnum;
import com.i2works.smartluolong.utils.base.CompanyMemberRoleEnum;
import com.i2works.smartluolong.utils.base.DateConstant;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.common.DateUtils;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.Implement.ImplementDO;
import com.i2works.smartluolong.web.entity.Implement.ImplementQuery;
import com.i2works.smartluolong.web.entity.company.*;
import com.i2works.smartluolong.web.entity.item.ItemApasinfoDO;
import com.i2works.smartluolong.web.entity.item.ItemApasinfoQuery;
import com.i2works.smartluolong.web.entity.item.ItemAttrDO;
import com.i2works.smartluolong.web.entity.item.ItemNodeDO;
import com.i2works.smartluolong.web.entity.item.ItemNodeQuery;
import com.i2works.smartluolong.web.service.company.ICompanyApplyImagesService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyMemberService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.i2works.smartluolong.web.service.flow.IFlowService;
import com.i2works.smartluolong.web.service.flow.IFlowTemplateService;
import com.i2works.smartluolong.web.service.implement.IImplementService;
import com.i2works.smartluolong.web.service.item.IItemApasinfoService;
import com.i2works.smartluolong.web.service.item.IItemAttrService;
import com.i2works.smartluolong.web.service.item.IItemNodeService;
import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 用户
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/3/20 16:45
 */

@RestController
@RequestMapping("/companyApplyMember")
public class CompanyApplyMemeberController extends CommonItemController {


	private final ICompanyApplyService companyApplyService;
    private final ICompanyApplyMemberService companyApplyMemberService;
    private final ICompanyApplyImagesService companyApplyImagesService;
    private final IItemApasinfoService  itemApasinfoService;
    private final IItemAttrService itemAttrService;
    private final IItemNodeService  itemNodeService;
    private final IImplementService implementService;

    @Autowired
    public CompanyApplyMemeberController(IFlowTemplateService flowTemplateService,
    		IFlowService flowService,
    		IFlowProcessService flowProcessService,
    		ICompanyApplyMemberService companyApplyMemberService, 
    		ICompanyApplyImagesService companyApplyImagesService,
    		ICompanyApplyService companyApplyService, 
    		IItemApasinfoService  itemApasinfoService,
    		IItemAttrService itemAttrService,
    		IItemNodeService  itemNodeService,
    		IImplementService implementService) {
        super(flowTemplateService, flowService, flowProcessService);
        this.companyApplyService = companyApplyService;
        this.companyApplyMemberService = companyApplyMemberService;
        this.companyApplyImagesService=companyApplyImagesService;
        this.itemApasinfoService=itemApasinfoService;
        this.itemAttrService=itemAttrService;
        this.itemNodeService=itemNodeService;
        this.implementService=implementService;
    }


    /**
     * 根据申请ID查询股东列表(只含股东信息)
     */
    @GetMapping("/shareholder/list/{applyId:\\d+}")
    public Result queryShareholder(@PathVariable(value = "applyId") Integer applyId) {
        CompanyApplyDO companyApply = getCompanyApply(applyId);
        if (companyApply == null) {
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
        //查询股东信息(回显)
        JSONObject shareHolderList = getShareHolderList(companyApply.getId());
        List shareholderList = shareHolderList.getObject("shareholderList", List.class);
        Integer shareholderCount = shareHolderList.getInteger("shareholderCount");
        return R.success(shareholderList, shareholderCount);
    }


    /**
     * 根据申请ID查询股东列表(含公司信息)
     */
    @GetMapping("/shareholder/{applyId:\\d+}")
    public Result getShareholder(@PathVariable(value = "applyId") Integer applyId) {
        JSONObject jsonObject = new JSONObject();
        CompanyApplyDO companyApply = getCompanyApply(applyId);
        if (null == companyApply) {
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
        jsonObject.put("companyApply", companyApply);
        jsonObject.putAll(getShareHolderList(companyApply.getId()));
        return R.success(jsonObject);
    }


    /**
     * 添加股东人信息
     */
    @PostMapping("/shareholder/save")
    public Result saveShareholder(CompanyApplyParams params) {
        List<CompanyApplyMemberDO> shareholderList = params.getMemberList();
        if (CollectionUtil.isEmpty(shareholderList) && shareholderList.get(0).getApplyId() == null) {
            return R.error(MsgEnum.ATTRS_EMPTY.getMsg());
        }
        try {
            //根据applyId + user.roleId 删除所有股东，然后再新增
            CompanyApplyMemberQuery memberQuery = new CompanyApplyMemberQuery();
            memberQuery.setRole(CompanyMemberRoleEnum.ROLE_1.getKey());
            memberQuery.setApplyId(shareholderList.get(0).getApplyId());
            companyApplyMemberService.deleteShareholderByRole(memberQuery);
            //删除完成过后，再循环添加
            for (CompanyApplyMemberDO memberDO : shareholderList) {
                //设置角色
                memberDO.setRole(CompanyMemberRoleEnum.ROLE_1.getKey());
                //出资类型
                memberDO.setInvestmentMode(BaseUtils.listToStr(memberDO.getInvestmentModeList(), ","));
                //创建人
                memberDO.setUpdateName(getUserName());
                //状态
                memberDO.setStatus(GlobalConstant.status.TRUE);
                companyApplyMemberService.saveOrUpdate(memberDO);
            }
        } catch (ServiceException e) {
            logger.error("添加股东人信息异常：" + e.getMessage());
            return R.error(MsgEnum.ATTRS_EMPTY.getMsg());
        }
        return R.success();
    }


    /**
     * 查询公司某个职工（法人、监事、经理等）信息
     */
    @GetMapping("/{memberKey:^legal$|^director$|^manager$|^supervisor$|^financial$|^contact$|^operator$}/{applyId:\\d+}")
    public Result getMember(@PathVariable(value = "memberKey") String memberKey, @PathVariable(value = "applyId") Integer applyId) {
        JSONObject jsonObject = new JSONObject();
        try {
            CompanyApplyQuery applyQuery = new CompanyApplyQuery();
            applyQuery.setId(applyId);
            CompanyApplyDO companyApplyDO = companyApplyService.query(applyQuery);
            if (null == companyApplyDO) {
                return R.error(MsgEnum.FIND_ERROR.getMsg());
            }
            //页面信息
            JSONObject memeberPageInfo = getMemeberIdInfo(memberKey);
            jsonObject.putAll(memeberPageInfo);
            //查询员工信息
            CompanyApplyMemberQuery memberQuery = new CompanyApplyMemberQuery();
            memberQuery.setApplyId(applyId);
            memberQuery.setIdentity(memeberPageInfo.getInteger("identityId"));
            memberQuery.setRole(CompanyMemberRoleEnum.ROLE_0.getKey());
            CompanyApplyMemberDO currentMember = companyApplyMemberService.query(memberQuery);
            if (currentMember == null) {
                jsonObject.put("member", new CompanyApplyMemberDO());
            } else {
                jsonObject.put("member", currentMember);
            }
        } catch (ServiceException e) {
            logger.error("添加法人信息异常：" + e.getMessage());
        }
        return R.success(jsonObject);
    }


    /**
     * 添加公司职工
     *
     * @param isLast 是否最后一个
     */
    @PostMapping("/{memberKey:^legal$|^director$|^manager$|^supervisor$|^financial$|^contact$|^operator$}/save")
    public Result saveMember(@PathVariable(value = "memberKey") String memberKey, @ModelAttribute CompanyApplyMemberDO companyApplyMemberDO) {
        try {
            //实体非空
            if (null == companyApplyMemberDO) {
                return R.error(MsgEnum.SAVE_ERROR.getMsg());
            }
            //查询申请ID是不是当前用户的
            CompanyApplyDO companyApply = getCompanyApply(companyApplyMemberDO.getApplyId());
            if (companyApply == null) {
                return R.error(MsgEnum.SAVE_ERROR.getMsg());
            }
            //获取人员身份参数
            JSONObject memeberIdInfo = getMemeberIdInfo(memberKey);
            //是否最后一步
            Boolean isLast = memeberIdInfo.getBoolean("isLast");
            //设置传递用户ID（工作流中使用）
            companyApply.setUserId(getUserId());
            //设置传递更新人姓名
            companyApplyMemberDO.setUpdateName(getUserName());
            // 保存（根据姓名、证件号、申请ID、身份ID来判断当前人是否存在，存在就更新，不存在就新增）
            companyApplyMemberService.saveMember(companyApplyMemberDO, companyApply, isLast);
            return R.success();
        } catch (ServiceException e) {
            logger.error("添加公司职工异常：" + e.getMessage());
            return R.error(MsgEnum.SAVE_ERROR.getMsg());
        }
    }

    /**
     * 获取需要签名的人员信息（股东/法人/代办人列表）
     */
    @GetMapping("/autograph/{applyId:\\d+}")
    public Result autograph(@PathVariable Integer applyId) {
        CompanyApplyMemberQuery memberQuery = new CompanyApplyMemberQuery();
        memberQuery.setApplyId(applyId);
        memberQuery.setDistinct(true);
        try {
            List<CompanyApplyMemberDO> list = companyApplyMemberService.queryComplementMemberList(memberQuery);
            if (CollUtil.isNotEmpty(list)) {
                return R.success(list, list.size());
            }
        } catch (ServiceException e) {
            logger.error("查询数据补全用户列表失败：" + e.getMessage(), applyId);
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
        return R.error(MsgEnum.FIND_ERROR.getMsg());
    }


    /**
     * 更新人员签名和自拍照的补充数据
     */
    @PostMapping("/autograph/save")
    public Result updateSupplement(CompanyApplyParams params) {
        List<CompanyApplyMemberDO> memeberList = params.getMemberList();
        try {
            if (CollUtil.isEmpty(memeberList)) {
                return R.error(MsgEnum.ATTRS_EMPTY.getMsg());
            }
            companyApplyMemberService.updateSupplement(memeberList, getLoginUser());
            SaveItemApasinfo(memeberList.get(0).getApplyId());//插入省统一申报表 
        } catch (ServiceException e) {
            logger.error("更新人员签名和自拍照的补充数据失败：" + e.getMessage());
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
        return R.success();
    }

    /**
     * 获取员工身份参数
     */
    private JSONObject getMemeberIdInfo(String memberKey) {
        JSONObject json = new JSONObject();
        switch (memberKey) {
            case "director":
                json.put("identityId", CompanyMemberIdentityEnum.ID_1.getKey());
                json.put("identityName", CompanyMemberIdentityEnum.ID_1.getText());
                json.put("isLast", false);
                break;
            case "manager":
                json.put("identityId", CompanyMemberIdentityEnum.ID_2.getKey());
                json.put("identityName", CompanyMemberIdentityEnum.ID_2.getText());
                json.put("isLast", false);
                break;
            case "supervisor":
                json.put("identityId", CompanyMemberIdentityEnum.ID_3.getKey());
                json.put("identityName", CompanyMemberIdentityEnum.ID_3.getText());
                json.put("isLast", false);
                break;

            case "legal":
                json.put("identityId", CompanyMemberIdentityEnum.ID_4.getKey());
                json.put("identityName", CompanyMemberIdentityEnum.ID_4.getText());
                json.put("isLast", false);
                break;
            case "financial":
                json.put("identityId", CompanyMemberIdentityEnum.ID_5.getKey());
                json.put("identityName", CompanyMemberIdentityEnum.ID_5.getText());
                json.put("isLast", false);
                break;
            case "contact":
                json.put("identityId", CompanyMemberIdentityEnum.ID_6.getKey());
                json.put("identityName", CompanyMemberIdentityEnum.ID_6.getText());
                json.put("isLast", false);
                break;
            case "operator":
                json.put("identityId", CompanyMemberIdentityEnum.ID_7.getKey());
                json.put("identityName", CompanyMemberIdentityEnum.ID_7.getText());
                json.put("isLast", true);
                break;
        }
        return json;
    }

    /**
     * 获取股东列表和数量统计
     */
    private JSONObject getShareHolderList(Integer applyId) {
        JSONObject jsonObject = new JSONObject();
        //查询股东信息(回显)
        CompanyApplyMemberQuery memberQuery = new CompanyApplyMemberQuery();
        memberQuery.setApplyId(applyId);
        memberQuery.setRole(CompanyMemberRoleEnum.ROLE_1.getKey());
        List<CompanyApplyMemberDO> shareholderList = null;
        try {
            Integer queryCount = companyApplyMemberService.queryCount(memberQuery);
            if (queryCount > 0) {
                shareholderList = companyApplyMemberService.queryList(memberQuery);
            }
            jsonObject.put("shareholderList", shareholderList);
            jsonObject.put("shareholderCount", queryCount);
        } catch (ServiceException e) {
            logger.error("根据apply查询股东个人信息异常：" + e.getMessage());
        }
        return jsonObject;
    }


    /**
     * 查询申请实体(用户自己的)
     */
    private CompanyApplyDO getCompanyApply(Integer applyId) {
        CompanyApplyQuery applyQuery = new CompanyApplyQuery();
        applyQuery.setUserId(getUserId());
        applyQuery.setId(applyId);
        try {
            return companyApplyService.query(applyQuery);
        } catch (ServiceException e) {
            logger.error("申请编号{}查询失败：" + e.getMessage(), applyId);
        }
        return null;
    }

    
    
    private void SaveItemApasinfo(Integer id) {
      	   try{
    		     ImplementQuery query=new ImplementQuery();
    		     query.setServiceCode("K24514909XK65834006");
    		     query.setStatus("Y");
    		     ImplementDO  implement=implementService.query(query);
    		     ItemApasinfoDO apasinfo=new ItemApasinfoDO();
    	         String projectId=null;
    	    	 projectId=createProjectId(implement.getDeptCode());
    	    	 /**
    	    	  * 公司申请表加projId
    	    	  * */
    		     CompanyApplyQuery comQuery=new CompanyApplyQuery();
    		     comQuery.setId(id);
    		     CompanyApplyDO companyApply =companyApplyService.query(comQuery);
    		     companyApply.setId(id);
    		     companyApply.setProjectId(projectId);
    		     companyApplyService.update(companyApply);
    	    	 apasinfo.setProjId(projectId);
    	    	 apasinfo.setProjPwd(createProjectPWD());
    	    	 apasinfo.setServiceCode(implement.getServiceCode());
    	    	 apasinfo.setServiceName(implement.getServiceName());
    	    	 apasinfo.setInfoType(implement.getInfoType());
    	    	 CompanyApplyMemberQuery memberQuery=new CompanyApplyMemberQuery();
    	    	 memberQuery.setApplyId(companyApply.getId());
    	    	 memberQuery.setIdentity(4);//法人代表
    	    	 memberQuery.setStatus(1);
    	    	 CompanyApplyMemberDO legal= companyApplyMemberService.query(memberQuery);
    	    	 apasinfo.setApplyName(legal.getName());
    	    	 apasinfo.setApplyCardType("身份证");
    	    	 apasinfo.setApplyCardNumber(legal.getCardNumber());
    	    	 memberQuery.setIdentity(6);//联系人
    	    	 CompanyApplyMemberDO contectMan= companyApplyMemberService.query(memberQuery);
    	    	 apasinfo.setContactMan(contectMan.getName());
    	    	 apasinfo.setContactManCardType("身份证");
    	    	 apasinfo.setContactManCardNumber(contectMan.getCardNumber());
    	    	 apasinfo.setTelphone(contectMan.getPhone());
    	    	 apasinfo.setPhone(contectMan.getPhone());
    	    	 apasinfo.setPostCode("");
    	    	 apasinfo.setAddress(companyApply.getCompanyAddress());
    	    	 apasinfo.setDeptCode(implement.getDeptCode());
    	    	 apasinfo.setDeptName(implement.getDeptName());
    	    	 apasinfo.setApplyFrom("政务服务网");
    	    	 apasinfo.setApplyType(implement.getApplyType());
    	    	 apasinfo.setApplyPropertiy(implement.getApplyPropertiy());
    	    	 apasinfo.setReceiveTime(companyApply.getCreateTime());
    	    	 apasinfo.setPromiseDays(implement.getPromiseDays());
    	    	 apasinfo.setLegalDays(implement.getLegalDays());
    	    	 apasinfo.setHandleState("收件");//办理状态
    	    	 apasinfo.setAreaCode(implement.getAreaCode());
    	    	 String belongSystem = apasinfo.getAreaCode()+apasinfo.getDeptCode()+"001";
    	    	 apasinfo.setBelongSystem(belongSystem);
    	    	 apasinfo.setReceiveUserid(getUserOpenId());
    	    	 apasinfo.setReceiveName(getUserName());
    	    	 apasinfo.setQlKind(getQLKind(implement.getServiceType()));
    	    	 apasinfo.setCreateName(companyApply.getCreateName());
    	    	 apasinfo.setUpdateName(companyApply.getUpdateName());
    	    	 apasinfo.setSyncStatus("I");
    	    	 saveAttr(companyApply);
    			 ItemNodeDO  itemNode=new ItemNodeDO();
    			 itemNode.setProjId(apasinfo.getProjId());
    	         itemNode.setAction("收件");
    	         itemNode.setOpinion("电子件已接收");
    	         itemNode.setNodeName("收件");
    	         itemNode.setName(apasinfo.getApplyName());
    	         itemNode.setStartTime(new Date());
    	         itemNode.setEndTime(new Date());
    	         itemNode.setBelongSystem(apasinfo.getBelongSystem());
    	         itemNode.setCreateTime(new Date());
    	         itemNode.setDataVersion(1);
    	         itemNode.setNextNodeName("受理");
    	         itemNode.setAreaCode(apasinfo.getAreaCode());
    	         itemNode.setHanderDeptId(apasinfo.getDeptCode());
    	         itemNode.setHanderDeptName(apasinfo.getDeptName());
    	         itemNode.setPhaseName("申报阶段");
    	         itemNode.setPhaseCode("01");
    	         itemNode.setSyncStatus("I");
    			 itemNodeService.save(itemNode);
    	    	 apasinfo.setDataVersion(1);
    	    	 apasinfo.setFlowXml(getFlowXML(apasinfo));//流程xml
    			 itemApasinfoService.save(apasinfo);
    	    } catch (ServiceException e) {
    	      logger.error("apasinfo收件环节插入异常"+e.getMessage());
    	    }
    }
    
    /**
     * 处理附件
     *
     * @param companyApplyId 公司申请id
     */
    private void saveAttr(CompanyApplyDO companyApply) throws ServiceException {
    	CompanyApplyImagesQuery imagesQuery=new CompanyApplyImagesQuery();
    	imagesQuery.setApplyId(companyApply.getId());
    	imagesQuery.setStatus(1);
        List<CompanyApplyImagesDO> list=companyApplyImagesService.queryList(imagesQuery);
        for (CompanyApplyImagesDO imagesDO : list) {
        	  ItemAttrDO attrDO = new ItemAttrDO();
              attrDO.setCreateName(getUserName());
              attrDO.setProjId(companyApply.getProjectId());
              attrDO.setAttrName("有限责任公司设立登记申请材料");
              attrDO.setFileUrl(imagesDO.getImg());
              attrDO.setFileName("有限责任公司设立登记申请材料");
              itemAttrService.save(attrDO);
		}
    }
    

    /**
     * 
     * 生成办件编号
     * */
    private String createProjectId(String deptCode) {
  	  String projId=null;
  	  int num=1;
  	  try {
  		  int length=deptCode.length();
  		  String applyDate = DateUtils.get(new Date(), DateConstant.YYMMDD);
  		  ItemApasinfoQuery query=new ItemApasinfoQuery();
  		  query.setReceiveTime(DateUtils.str2Date(applyDate, DateConstant.YYMMDD));
  		  query.setDeptCode(deptCode);
  		  num = itemApasinfoService.queryCount(query);
  		  num=num+1;
  		  projId = "410311" +deptCode.substring(length-3)+ applyDate + '1' + String.format("%06d", num);
  	  } catch (ServiceException e) {
  		  e.printStackTrace();
  	  }
  	  return projId;
    }
    
    /**
     * 生成查询密码
     * 
     * */
    private String createProjectPWD() {
  	  String sources = "0123456789"; 
  		Random rand = new Random();
  		StringBuffer flag = new StringBuffer();
  		for (int j = 0; j < 6; j++) 
  		{
  			flag.append(sources.charAt(rand.nextInt(9)) + "");
  		}
  	  return flag.toString();
    }
    
    
    /**
     * 生成流程XML
     */
    private String getFlowXML(ItemApasinfoDO apasinfoDO) {
            String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\r\n<NODES>\r\n";
            try {
            List<ItemNodeDO> list=Lists.newArrayList();
            ItemNodeQuery query=new ItemNodeQuery();
            query.setProjId(apasinfoDO.getProjId());
            query.setOrder(0);
            Integer	count = itemNodeService.queryCount(query);
            if(count>0) {
          	  list=itemNodeService.queryList(query);
          	  int step=1;
          	  for (ItemNodeDO itemNodeDO : list) {
                    xml += "<NODE>\r\n" +
                            "    <NODENAME>"+itemNodeDO.getNodeName()+"</NODENAME>\r\n" +
                            "    <STEP>"+step+"</STEP>\r\n" +
                            "    <STATE>"+(4-step)+"</STATE>\r\n" +
                            "    <TIMELIMIT>"+apasinfoDO.getPromiseDays()+"</TIMELIMIT>\r\n"+
                            "    <STARTTIME>"+DateUtils.get(itemNodeDO.getStartTime(), DateConstant.ALL)+"</STARTTIME>\r\n"+
                            "    <ENDTIME>"+DateUtils.get(itemNodeDO.getEndTime(), DateConstant.ALL)+"</ENDTIME>\r\n"+
                            "    <STAYTIME>0</STAYTIME>\r\n"+
                            "    <OPINION>" + itemNodeDO.getOpinion() + "</OPINION>\r\n" +
                            "    <NAME>"+itemNodeDO.getName()+"</NAME>\r\n" +
                            "    <TEL>"+apasinfoDO.getPhone()+"</TEL>\r\n" +
                            "</NODE>\r\n";
                    step++;
  			  }
            }
            xml += "</NODES>";
  		} catch (ServiceException e) {
  			e.printStackTrace();
  		}
        return xml;
    }
    /**
     * 获取权力类型
     * */
    
    private String getQLKind(String  key){
    	Map<String, String> map =new HashMap<String, String> ();
    		map.put("XK", "行政许可");
    		map.put("JC", "行政检查");
    		map.put("QZ", "行政强制");
    		map.put("ZC", "行政征收");
    		map.put("GF", "行政给付");
    		map.put("CJ", "行政裁决");
    		map.put("QR", "行政确认");
    		map.put("JL", "行政奖励");
    		map.put("GG", "公共服务");
    		map.put("QT", "其他权力");
    		String QLKing=map.get(key);
    	return QLKing;
    }


}
